package com.paradise.phone.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.paradise.api.FaceCall;
import com.paradise.api.FacePhone;
import com.paradise.phone.OnRecyclerViewItemClickListener;
import com.paradise.phone.R;
import com.paradise.phone.adapter.HistoryAdapter;
import com.paradise.phone.utils.DataBaseHelper;
import com.paradise.phone.utils.MyItemDecoration;
import com.paradise.phone.utils.PinyinUtils;
import com.paradise.phone.utils.ToastUtil;

import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.linphone.core.CallDirection;
import org.linphone.core.LinphoneAddress;
import org.linphone.core.LinphoneCallLog;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Sisyphus on 2017/9/21.
 */

public class HistoryFragment extends Fragment implements OnRecyclerViewItemClickListener {

    private View rootView;

    private RecyclerView rvCallLog;
    private HistoryAdapter ha;

    private LinphoneCallLog[] mCallLogs;
    private AlertDialog addContactDialog;
    private Dialog historyDetailDialog;
    private SQLiteDatabase db;

    private int currentPos;
    private View detailView;
    private TextView tvDisplayName;
    private TextView tvProxy;
    private TextView tvState;
    private TextView tvStartTime;
    private TextView tvDuration;
    private TextView tvQuality;
    private ImageView ivClose;
    private Button btnCall;

    private SwipeRefreshLayout srlRefreshHistory;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_history, null);

        initView();

        initEvent();

        db = DataBaseHelper.instance(getActivity()).getWritableDatabase();

        return rootView;
    }

    private void initView(){
        rvCallLog = (RecyclerView) rootView.findViewById(R.id.rv_call_log);
        srlRefreshHistory = (SwipeRefreshLayout) rootView.findViewById(R.id.srl_refresh_history);

        srlRefreshHistory.setColorSchemeColors(Color.parseColor("#3fb559"));

        ha = new HistoryAdapter(getActivity());
        ha.setOnRecyclerViewItemClickLitener(this);
        mCallLogs = FacePhone.instance().getmLc().getCallLogs();
        ha.setData(mCallLogs);
        rvCallLog.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvCallLog.setAdapter(ha);
        rvCallLog.addItemDecoration(new MyItemDecoration());
    }

    private void initEvent(){
        srlRefreshHistory.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mCallLogs = FacePhone.instance().getmLc().getCallLogs();
                ha.setData(mCallLogs);
                ha.notifyDataSetChanged();
                srlRefreshHistory.setRefreshing(false);
            }
        });

    }

    @Override
    public void onRecyclerViewItemClickLitener(View view, int position) {
        currentPos = position;
        switch (view.getId()){
            case R.id.tv_delete:
                FacePhone.instance().getmLc().removeCallLog(mCallLogs[position]);
                mCallLogs = FacePhone.instance().getmLc().getCallLogs();
                ha.setData(mCallLogs);
                ha.notifyItemRemoved(position);
                break;

            case R.id.tv_add:
                showDialog();
                break;

            case R.id.ll_content:
                showDetailDiaglog();
                break;
        }
    }

    private void showDialog(){
        if (addContactDialog == null){
            View dialogView = LayoutInflater.from(getActivity())
                    .inflate(R.layout.dialog_add_contact, null);
            final EditText etRemarks = (EditText) dialogView.findViewById(R.id.et_add_display_name);
            final EditText etNumber = (EditText) dialogView.findViewById(R.id.et_add_username);
            TextView tvConfirm = (TextView) dialogView.findViewById(R.id.tv_add_confirm);
            TextView tvCancle = (TextView) dialogView.findViewById(R.id.tv_add_cancle);

            if (mCallLogs[currentPos].getDirection() == CallDirection.Outgoing){
                etRemarks.setText(mCallLogs[currentPos].getTo().getDisplayName());
                etNumber.setText(mCallLogs[currentPos].getTo().getUserName());
            }else {
                etRemarks.setText(mCallLogs[currentPos].getFrom().getDisplayName());
                etNumber.setText(mCallLogs[currentPos].getFrom().getUserName());
            }

            tvConfirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (TextUtils.isEmpty(etRemarks.getText())
                            || TextUtils.isEmpty(etNumber.getText())){
                        ToastUtil.showToast(getActivity(), "备注或号码为空");
                        return;
                    }

                    ContentValues values = new ContentValues();
                    values.put("remarks", etRemarks.getText().toString());
                    values.put("number", etNumber.getText().toString());
                    String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    values.put("create_time", createTime);
                    String pinyin = null;
                    try {
                        pinyin = new PinyinUtils().hanzi2Pinyin(etRemarks.getText().toString(),
                                "", PinyinUtils.Type.FIRSTUPPER);
                        values.put("pinyin", pinyin);
                    } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                        badHanyuPinyinOutputFormatCombination.printStackTrace();
                        return;
                    }
                    if (db.insert("Contact", null, values) != -1){
                        ToastUtil.showToast(getActivity(), "添加成功");
                        srlRefreshHistory.setRefreshing(true);
                        mCallLogs = FacePhone.instance().getmLc().getCallLogs();
                        ha.setData(mCallLogs);
                        ha.notifyDataSetChanged();
                        srlRefreshHistory.setRefreshing(false);
                        addContactDialog.dismiss();
                    }else {
                        ToastUtil.showToast(getActivity(), "添加失败");
                    }
                }
            });

            tvCancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    addContactDialog.dismiss();
                }
            });

            addContactDialog = new AlertDialog.Builder(getActivity())
                    .setView(dialogView)
                    .create();

            addContactDialog.setCancelable(false);
        }

        if (!addContactDialog.isShowing()){
            addContactDialog.show();
        }
    }

    private void showDetailDiaglog(){

        final LinphoneAddress address;

        if (mCallLogs[currentPos].getDirection() == CallDirection.Outgoing){
            address = mCallLogs[currentPos].getTo();
        }else {
            address = mCallLogs[currentPos].getFrom();
        }

        final String username = address.getUserName();

        if (historyDetailDialog == null){
            detailView = LayoutInflater.from(getActivity()).inflate(R.layout.history_detail, null);
            tvDisplayName = (TextView) detailView.findViewById(R.id.tv_detail_display_name);
            tvProxy = (TextView) detailView.findViewById(R.id.tv_detail_proxy);
            tvState = (TextView) detailView.findViewById(R.id.tv_detail_call_state);
            tvStartTime = (TextView) detailView.findViewById(R.id.tv_detail_start_time);
            tvDuration = (TextView) detailView.findViewById(R.id.tv_detail_duration);
            tvQuality = (TextView) detailView.findViewById(R.id.tv_detail_quality);
            ivClose = (ImageView) detailView.findViewById(R.id.iv_detail_close);
            btnCall = (Button) detailView.findViewById(R.id.btn_detail_call);

            historyDetailDialog = new Dialog(getActivity(), R.style.Theme_Light_Dialog);

            //获得dialog的window窗口
            Window window = historyDetailDialog.getWindow();
            //设置dialog在屏幕底部
            window.setGravity(Gravity.BOTTOM);
            //设置dialog弹出时的动画效果，从屏幕底部向上弹出
            window.setWindowAnimations(R.style.dialogStyle);
            window.getDecorView().setPadding(0, 0, 0, 0);
            //获得window窗口的属性
            android.view.WindowManager.LayoutParams lp = window.getAttributes();
            //设置窗口宽度为充满全屏
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            //设置窗口高度为包裹内容
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            //将设置好的属性set回去
            window.setAttributes(lp);

            historyDetailDialog.setContentView(detailView);
        }

        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                historyDetailDialog.dismiss();
            }
        });
        btnCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String displayName;
                Cursor cursor = db.rawQuery("select * from Contact where number = '"
                        +username+"'", null);
                if (cursor.getCount() == 0){
                    displayName = "未知联系人";
                }else {
                    cursor.moveToNext();
                    displayName = cursor.getString(1);
                }
                Log.d("flag->", "HistoryFragment.java(onClick:231)->username = "+username);
                FaceCall.instance().call(getActivity(), username, displayName);
            }
        });

        tvDisplayName.setText(address.getDisplayName());
        tvProxy.setText("sip:"+address.getUserName()+"@"+address.getDomain()+":5080");
        tvDuration.setText(mCallLogs[currentPos].getCallDuration()+"秒");
        tvStartTime.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(mCallLogs[currentPos].getTimestamp()));

        switch (mCallLogs[currentPos].getStatus().toInt()){
            case 0:
                tvState.setText("成功");
                break;
            case 1:
                tvState.setText("中止");
                tvQuality.setText("----");
                break;
            case 2:
                tvState.setText("漏接");
                tvQuality.setText("----");
                break;
            case 3:
                tvState.setText("拒接");
                tvQuality.setText("----");
                break;
        }

        if (!historyDetailDialog.isShowing()){
            historyDetailDialog.show();
        }
    }

}
